package ru.tests;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
public class GrabWaresFromUtkonos {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

/*
        System.setProperty("http.proxyHost", "db-isa-01");
        System.setProperty("http.proxyPort", "8080");
*/


//        FileInputStream fin = new FileInputStream("src\\main\\database\\wares_groups_lst.ser");
        FileInputStream fin = new FileInputStream("src\\main\\database\\wares_groups_lst_with_wares.ser");
        ObjectInputStream in = new ObjectInputStream(fin);
        List<WareGroup> roots = (List<WareGroup>) in.readObject();

        in.close();

        System.exit(111);

        Map<Integer, WareGroup> endGroups = new HashMap<Integer, WareGroup>();

        fillEndGroups(roots, endGroups);

        System.out.println(endGroups.size());

        //System.exit(111);

        for (WareGroup group : endGroups.values()) {

            readWaresOfGroupFromUrl(group, -1);
            System.out.println("Group[" + group.name + "] filled");
            //break;

        }
        //System.exit(111);
        FileOutputStream fout = new FileOutputStream("src\\main\\database\\wares_groups_lst_with_wares.ser");
        ObjectOutputStream out = new ObjectOutputStream(fout);
        out.writeObject(roots);
        out.close();

    }

    private static void fillEndGroups(List<WareGroup> groups, Map<Integer, WareGroup> endGroups) {
        for (WareGroup group : groups) {
            group.wares = new ArrayList<WareUtkonos>();
            if (group.childs.size() == 0) {
                endGroups.put(group.id, group);
            } else {
                fillEndGroups(group.childs, endGroups);
            }
        }
    }

    private static void readWaresOfGroupFromUrl(WareGroup group, int page) throws IOException {
        //System.out.println(group.utkonosID + " page[" + page + "]");
        URL url = new URL("http://www.utkonos.ru/cat/" + group.utkonosID + "/" + ((page != -1) ? "pg" + page + "/" : ""));
        URLConnection connection = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "CP1251"));
        String inputLine;

        int maxPage = 0;
        List<WareUtkonos> wares = new ArrayList<WareUtkonos>();
        WareUtkonos curWare = null;
        while ((inputLine = in.readLine()) != null) {

            if (inputLine.startsWith("<a class=\"page current\">")) {
                if (maxPage == 0) {
                    String str1 = "<a class=\"page last\" href=\"/cat/" + group.utkonosID + "/pg";
                    int i1 = inputLine.indexOf(str1);
                    inputLine = inputLine.substring(i1 + str1.length());
                    String lastPageStr = inputLine.substring(0, inputLine.indexOf("/\">"));
                    maxPage = Integer.parseInt(lastPageStr);
                }
            } else {
                if (inputLine.indexOf("<!--Товар в списке-->") != -1) {
                    curWare = new WareUtkonos();
                    group.wares.add(curWare);
                } else {
                    if (curWare != null) {
                        if (inputLine.trim().startsWith("<span>Артикул:</span>")) {
                            String idStr = inputLine.substring("<span>Артикул:</span>".length(), inputLine.indexOf("</div>")).trim();
                            //System.out.println("wareID: " + idStr);
                            curWare.utkonosID = Integer.parseInt(idStr.substring(1));
                        } else if (inputLine.trim().startsWith("<td class=\"picture\"><div class=\"item_picture\"><div class=\"picture_container\">")) {
                            int i1 = inputLine.indexOf("<img src=\"");
                            inputLine = inputLine.substring(i1 + "<img src=\"".length());
                            String impUrl = inputLine.substring(0, inputLine.indexOf('"'));
                            //System.out.println("impUrl: " + impUrl);
                            curWare.imgUrl = impUrl;
                        } else if (inputLine.trim().startsWith("<div class=\"price\"><span class=\"price_value\">")) {
                            inputLine = inputLine.substring("<div class=\"price\"><span class=\"price_value\">".length());
                            String price = inputLine.substring(0, inputLine.indexOf("<span"));
                            //System.out.println("WarePrice: " + price);
                            curWare.price = price;
                        } else if (inputLine.trim().startsWith("<div class=\"title\"><a class=\"name\" href=")) {
                            inputLine = inputLine.substring("<div class=\"title\"><a class=\"name\" href=".length());
                            int i1 = inputLine.indexOf("/\">");
                            int i2 = inputLine.indexOf("</a>");
                            String name = inputLine.substring(i1 + "/\">".length(), i2);
                            curWare.name = name;
                            //System.out.println("WareName: " + name);
                        }
                    }
                }
            }

        }
        in.close();

        //System.out.println("maxPage: " + maxPage);
/* */
        if (page == -1) {
            for (int i=2; i<=maxPage; i++) {
                readWaresOfGroupFromUrl(group, i);
            }
        }
/* */

    }

}
